package com.book.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.mapper.FavoritesMapper;
import com.book.pojo.Favorites;
import com.book.pojo.FavoritesVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author icatw
 * @date 2022/4/8
 * @email 762188827@qq.com
 * @apiNote
 */
@Service
@Transactional
@Slf4j
public class FavoritesService extends ServiceImpl<FavoritesMapper, Favorites> {
    @Autowired
    BookService bookService;

    /**
     * 展示用户收藏列表（只展示收藏状态的）
     *
     * @param id id
     * @return {@link List}<{@link FavoritesVo}>
     */
    public List<FavoritesVo> findUserFavorites(Integer id) {
        List<FavoritesVo> voList = this.baseMapper.findUserFavorites(id);
        return voList;
    }

    /**
     * 根据用户id和书id查找收藏
     *
     * @param userId 用户id
     * @param bookId 书id
     * @return {@link Favorites}
     */
    public Favorites findUserFavorites(Integer userId, Integer bookId) {
        //TODO 收藏状态
        return this.baseMapper.selectOne(new QueryWrapper<Favorites>().eq("user_id", userId)
                .eq("book_id", bookId));
    }

    /**
     * 更新状态通过用户id和书id
     * 取消收藏
     * @param userId 用户id
     * @param bookId 书id
     */
    public void updateStatusByUserIdAndBookId(Integer userId, Integer bookId) {

        Favorites userFavorites = this.findUserFavorites(userId, bookId);
        //取消收藏，设置状态为0
        userFavorites.setStatus(0);
        this.baseMapper.updateById(userFavorites);
    }

    /**
     * 更新收藏状态
     * 添加收藏
     * @param userId 用户id
     * @param bookId 书id
     */
    public void updateStatus(Integer userId, Integer bookId) {
        Favorites userFavorites = this.findUserFavorites(userId, bookId);
        if (userFavorites != null) {
            //如果当前书籍之前收藏过 则更新收藏状态
            userFavorites.setStatus(1);
            this.baseMapper.updateById(userFavorites);
        } else {
            //没收藏过，新增收藏记录
            Favorites favorites = new Favorites();
            favorites.setUserId(userId);
            favorites.setBookId(bookId);
            this.baseMapper.insert(favorites);
        }

    }
}
